//
//  DBTool.m
//  Eyeshot
//
//  Created by lanou3g on 15/7/3.
//  Copyright (c) 2015年 lanou3g.com. All rights reserved.
//数据库

#import "DBTool.h"
#import "FMDB.h"
@implementation DBTool

static FMDatabase *_db;
+ (void)initialize{
    //1.打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"dailyList.sqlite"];
    _db = [FMDatabase databaseWithPath:path];
    NSLog(@"path ---- %@",path);
    [_db open];
    //2.创建表
    //tableView数据表
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_dailyList (id integer PRIMARY KEY, dailyList blob NOT NULL,date text NOT NULL);"];
    //缓存路径表
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_wxl (id integer PRIMARY KEY, path TEXT NOT NULL,title text NUT NULL);"];
    
}

#pragma mark - tableView
//1.根据参数请求去沙盒中加载缓存数据
+ (NSArray *)dataArrayWithParams:(NSMutableDictionary *)params{
    NSString *sql = @"SELECT * FROM t_dailyList ORDER BY date DESC LIMIT 10;";
    //执行SQL
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *dataArray = [[NSMutableArray alloc] init];
    while (set.next) {
        NSData *dataArrayData = [set objectForColumnName:@"dailyList"];
        NSDictionary *data = [NSKeyedUnarchiver unarchiveObjectWithData:dataArrayData];
        [dataArray addObject:data];
    }
    return dataArray;
}
//2.存储数据
+ (void)saveArray:(NSArray *)dataArray{
    //要将一个对象存进数据库的block字段,最好先转化成NSdata对象
    for (NSDictionary *dataDic in dataArray) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dataDic];
        [_db executeUpdateWithFormat:@"INSERT INTO t_dailyList(dailyList,date) VALUES (%@,%@);",data,dataDic[@"date"]];
    }
}
//3.移除所有数据
+ (void)removeAllData{
    [_db executeUpdateWithFormat:@"DELECT FROM t_dailyList"];
}

#pragma mark- 缓存路径
//1.存取数据
+ (void)savePath:(NSString *)path title:(NSString *)titleStr{
    [_db executeUpdateWithFormat:@"INSERT INTO t_wxl(path,title) VALUES (%@,%@);",path,titleStr];
}
//2.根据title读取数据
+ (NSString *)readPathTitle:(NSString *)titleStr{
    //1.SQL语句
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_wxl;"];
    //2.执行sql语句
    FMResultSet *set = [_db executeQuery:sql];
    NSString *titleStr2 = [[NSString alloc] init];
    NSString *pathStr = [[NSString alloc] init];
    while (set.next) {
        titleStr2 = [set stringForColumn:@"title"];
        if ([titleStr isEqualToString:titleStr2]) {
            pathStr = [set stringForColumn:@"path"];
        }
        NSLog(@"11%@",pathStr);
    }
    return pathStr;
}
//3.根据title删除数据
+ (void)deletePathByTitle:(NSString *)titleStr{
    [_db executeUpdate:@"DELETE TABLE IF EXISTS t_wxl WHERE title = %@;",titleStr];
}

@end
